<template>
  <div class="app">
    <div v-if="currentPage === 'login'">
      <LoginPage 
        @login-success="handleLoginSuccess"
      />
    </div>
    <div v-else-if="currentPage === 'vehicles'">
      <VehicleListPage 
        :vehicles="vehicles"
        :loading-vehicles="loadingVehicles"
        @go-back="handleGoBack"
        @vehicle-click="handleVehicleClick"
      />
    </div>
    
    <!-- Road View Modal -->
    <RoadView 
      v-if="showRoadModal"
      :user-car-id="selectedUserCarId"
      @go-back="closeRoadModal"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import LoginPage from './pages/Login.vue'
import VehicleListPage from './pages/VehicleList.vue'
import RoadView from './pages/RoadView.vue'
import { getStoreList, getTaskList } from './api/index.js'
import { getToken } from './http/request.js'

const currentPage = ref('login')
const vehicles = ref([])
const loadingVehicles = ref(false)
const selectedUserCarId = ref('')
const showRoadModal = ref(false)

function handleLoginSuccess(vehicleList) {
  vehicles.value = vehicleList
  loadingVehicles.value = false
  currentPage.value = 'vehicles'
}

function handleGoBack() {
  currentPage.value = 'login'
  vehicles.value = []
}

function handleVehicleClick(vehicle) {
  // Use userCarId if available, otherwise fall back to clientVehicleId
  const userCarId = vehicle.userCarId || vehicle.clientVehicleId
  
  if (!userCarId) {
    alert('车辆信息不完整，无法查看车路数据')
    return
  }
  
  selectedUserCarId.value = userCarId
  showRoadModal.value = true
}

function closeRoadModal() {
  showRoadModal.value = false
  selectedUserCarId.value = ''
}

async function initializeWithExistingToken() {
  loadingVehicles.value = true
  vehicles.value = []
  currentPage.value = 'vehicles'

  try {
    const stores = await getStoreList()
    let selectedStore = stores.find(store => store.selected)

    if (!selectedStore && stores.length > 0) {
      selectedStore = stores[0]
    }

    if (!selectedStore) {
      throw new Error('未找到可用门店')
    }

    const taskListParams = {
      current: 1,
      size: 10,
      dataScope: 'GARAGE',
      dataModel: 'CLIENT',
      code: 'MAINT',
      clientType: ['2', '5'],
      storeId: selectedStore.code,
      orders: {
        column: 'serviceDateTimestamp',
        asc: false
      }
    }

    const vehicleList = await getTaskList(taskListParams)
    vehicles.value = vehicleList
  } catch (error) {
    console.error('自动登录失败:', error)
    alert('自动登录失败，请重新选择账号: ' + (error.message || '未知错误'))
    currentPage.value = 'login'
  } finally {
    loadingVehicles.value = false
  }
}

onMounted(() => {
  const token = getToken()
  if (token) {
    initializeWithExistingToken()
  }
})
</script>

<style scoped>
.app {
  width: 100%;
  min-height: 100vh;
  background: #f5f7fa;
}
</style>
